package com.jagochan.module.springai.controller;

import com.jagochan.module.springai.common.repository.ChatHistoryRepository;
import com.jagochan.module.springai.pojo.MessageVO;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.ai.chat.messages.MessageType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@RequestMapping("/ai/history")
@RestController
public class ChatHistoryController {

    private final ChatHistoryRepository chatHistoryRepository;
    private final ChatMemory chatMemory;

    @ApiOperation(value = "查询会话历史列表")
    @GetMapping("/{type}")
    public Set<String> queryChatIdHistory(@ApiParam("聊天类型") @PathVariable String type) {
        return chatHistoryRepository.list(type);
    }

    @ApiOperation(value = "根据聊天ID（会话ID）查询聊天记录内容")
    @GetMapping("/{type}/{chatId}")
    public List<MessageVO> queryMessageByChatId(@ApiParam("聊天类型") @PathVariable String type,
                                                @ApiParam("聊天ID") @PathVariable String chatId) {
        return chatMemory.get(chatId, Integer.MAX_VALUE).stream()
                // 只查询USER和ASSISTANT类型的消息
                .filter(message -> message.getMessageType() == MessageType.USER || message.getMessageType() == MessageType.ASSISTANT)
                // 把SpringAI中的Message转换成MessageVO
                .map(message -> new MessageVO(message.getMessageType().getValue(), message.getText())).collect(Collectors.toList());
    }

}
